/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import doa.MessageDAO;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import models.Message;
import models.Twitterer;
import utils.JSFSessionHandler;

/**
 *
 * @author Misja
 */
public class MessageOverviewBean implements Serializable {

    private List<Message> messages;
    private Twitterer owner;

    public MessageOverviewBean() {
        this.owner = (Twitterer) JSFSessionHandler.getObjectFromSession("selectedUser");
        this.messages = MessageDAO.getMessagesByOwner(owner);
        //FacesContext.getCurrentInstance().getExternalContext().getFlash().get("twitterer");  
        //FacesContext.getCurrentInstance().getExternalContext().getFlash().keep("twitterer");
    }

    public List<Message> getMessages() {
        return messages;
    }

    public Twitterer getOwner() {
        return owner;
    }

    public void setOwner(Twitterer owner) {
        this.owner = owner;
    }

    public void setMessages(List<Message> messages) {
        this.messages = messages;
    }

    public void initMessages(Twitterer twitterer) {
        this.messages = MessageDAO.getMessagesByOwner(twitterer);
    }

    public void likeMessage(Message message) {
        Set<Twitterer> likes = message.getLikes();
        Twitterer currentUser = (Twitterer) JSFSessionHandler.getObjectFromSession("currentUser");
        if (currentUser.isPlatinumTwitterer()) {
            likes.add(currentUser);
            message.setLikes(likes);
            boolean result = MessageDAO.updateMessage(message);
            if (result) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Message is succesfully updated", null));
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Message couldnt be updated", null));
            }
        }
    }

    public String toTwittererOverView() {
        return "/TwittererOverview.xhtml?faces-redirect=true";
    }
}
